package com.academy.student;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;

import com.academy.querystapp.HomeActivity;
import com.academy.querystapp.R;
import com.academy.services.BaseService;
import com.academy.services.RequestMethod;
import com.academy.services.ResponseListener;
import com.academy.util.AcademyUtility;

public class StudentActivity extends Activity implements OnClickListener,ResponseListener
{
	Button btnRegistration,btnLogin;
	EditText edtMobileNo,edtPassword;
	
	
	
	
	String strUserName,strPassword;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_student);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		initializeViews();        
        
//		if(!chkWiFi())
//        {
//        	Builder builder = new Builder(StudentActivity.this);
//			builder.setTitle("Network Failed");
//			builder.setMessage("Please Check Your Network Setting and Try again")
//			.setCancelable(false)			          
//			.setPositiveButton("Ok", new DialogInterface.OnClickListener() 
//			{
//				public void onClick(DialogInterface dialog, int id) 
//				{	
//					finish();
//					dialog.dismiss();
//				}
//			}  
//            );
//			final AlertDialog alert = builder.create();	
//			alert.show();
//        }
    
		
	}

	public void initializeViews()
	{
		edtMobileNo=(EditText) findViewById(R.id.edtMobileNo);
		edtPassword=(EditText) findViewById(R.id.edtPassword);
		btnLogin=(Button) findViewById(R.id.btnLogin);
		btnRegistration=(Button) findViewById(R.id.btnRegistration);
		
		btnLogin.setOnClickListener(this);
		btnRegistration.setOnClickListener(this);
		
	}

	@Override
	public void onClick(View v) 
	{
		if(v==btnLogin)
		{
			strUserName=edtMobileNo.getText().toString().trim();
			strPassword=edtPassword.getText().toString().trim();
			
			if(strUserName.equals("")&& strPassword.equals(""))
			{
				
				Builder builder = new Builder(this);
				builder.setTitle("Login");
				builder.setMessage("Please Enter the Username and Password!");
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int arg1)
					{	
						dialog.dismiss();
					}
				});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}
			else if(strUserName.equals(""))
			{
				
				Builder builder = new Builder(this);
				builder.setTitle("Login");
				builder.setMessage("Please Type ur Username!");
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int arg1)
					{	
						dialog.dismiss();
					}
				});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}
			else if(strUserName.length()<8||strUserName.length()>8)
			{
				
				Builder builder = new Builder(this);
				builder.setTitle("Login");
				builder.setMessage("Please Enter your 8 digit Student ID !");
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int arg1)
					{	
						dialog.dismiss();
					}
				});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}
			else if(strPassword.equals(""))
			{
				
				Builder builder = new Builder(this);
				builder.setTitle("Login");
				builder.setMessage("Please Type ur password!");
				builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
				{
					public void onClick(DialogInterface dialog, int arg1)
					{	
						dialog.dismiss();
					}
				});
				AlertDialog alertDialog = builder.create();
				alertDialog.show();
			}			
			else
			{				
				
		    					
				BaseService baseService = new BaseService(this, this, RequestMethod.GET);
				baseService.addParam(getString(R.string.userName_param), edtMobileNo.getText().toString());
				baseService.addParam(getString(R.string.userType_Param),"Student");
				baseService.execute(getString(R.string.loginStudentURL));
		    					
		    				      
		    				      	
		    				     
			}
		}
		
		if(v==btnRegistration)
		{
			Intent ii=new Intent(this,StudentRegistration.class);
			startActivity(ii);
		}		
	}
	
	public boolean chkWiFi()
	{
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		if( ni != null && ni.getType() == ConnectivityManager.TYPE_WIFI )
		{
			return true;			
		}
		else
		{			
			return false;			
		}
	}
	
//	public void onBackPressed() 
//	{
//		   Intent back=new Intent(getApplicationContext(),HomeActivity.class);
//		   startActivity(back);
//		   this.finish();
//
//	}
	
	@Override
	public boolean dispatchTouchEvent(MotionEvent event) {

	    View v = getCurrentFocus();
	    boolean ret = super.dispatchTouchEvent(event);

	    if (v instanceof EditText) {
	        View w = getCurrentFocus();
	        int scrcoords[] = new int[2];
	        w.getLocationOnScreen(scrcoords);
	        float x = event.getRawX() + w.getLeft() - scrcoords[0];
	        float y = event.getRawY() + w.getTop() - scrcoords[1];

	        Log.d("Activity", "Touch event "+event.getRawX()+","+event.getRawY()+" "+x+","+y+" rect "+w.getLeft()+","+w.getTop()+","+w.getRight()+","+w.getBottom()+" coords "+scrcoords[0]+","+scrcoords[1]);
	        if (event.getAction() == MotionEvent.ACTION_UP && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w.getBottom()) ) { 

	            InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
	            imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
	        }
	    }
	return ret;
	}

	
	private void parseResponse(String response)
	{
		if(response==null ||response.equals("null"))
		{
			System.out.println("Response ---> "+response);
						
			showAlert(null, "No Server Found!");
		}
		else
		{
			try 
			{ 
			
				JSONObject RootObject = new JSONObject(response);
				System.out.println("JSON Object==> "+RootObject.toString());
				JSONObject studentObject = RootObject.getJSONObject("student");
				JSONObject studentData=studentObject.getJSONObject("StudentData");
				String strStatus=studentData.getString("status");
				System.out.println("studentData="+studentData);

				if(strStatus.equals("true"))
				{					
//					showAlert(null, "Logged in");
					AcademyUtility.setName(studentData.getString("studentName"));
					AcademyUtility.setCollegeName(studentData.getString("collageName"));
					AcademyUtility.setCoarse(studentData.getString("course"));
					AcademyUtility.setEmailID(studentData.getString("emailID"));
					AcademyUtility.setStudentID(strUserName);
					Intent ii=new Intent(this,QueryTabActivity.class);
					startActivity(ii);
				}
				else if(strStatus.equals("false"))
				{
					String strError= studentData.getString("errorDesc");
					showAlert(null, strError);
				}
			}
			catch (JSONException e) 
			{
				e.printStackTrace();
			} 
		}
	}
	
	
	public void showAlert(String Title,String Message)
	{
		Builder builder = new Builder(this);
		builder.setTitle(Title);
		builder.setMessage(Message);
		builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
		{
			public void onClick(DialogInterface dialog, int arg1)
			{	
//				Intent i=new Intent(StudentActivity.this,Homepage.class);
//				startActivity(i);
//				finish();						
			}
		});
		AlertDialog alertDialog = builder.create();
		alertDialog.show();	
	}

	@Override
	public void onServiceCompleted(String response, String requestURL) {
		parseResponse(response);
		
	}

	@Override
	public void onServiceFailed(String exception, String requestURL) {
		// TODO Auto-generated method stub
		
	}
	
}
